package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import board.Board2;
import board.Board2DAOIbatis;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class BoFrontController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);

	}

	private void execute(HttpServletRequest req, HttpServletResponse resp) {
		String uri=req.getRequestURI();
		System.out.println("uri="+uri);
		
		String contextPath=req.getContextPath();
		System.out.println("contextPath="+contextPath);
		
		String command = uri.substring(contextPath.length());
		System.out.println("command="+command);
		
		try {
			
			req.setAttribute("login", "login/LoginForm.jsp");
			req.setAttribute("side", "/template/side.jsp");
			req.setAttribute("body", "studyContent.jsp");
			
			if(command.equals("/boardWriteForm.bo")) {
				req.setAttribute("body", "board/boardWriteForm.jsp");
				req.getRequestDispatcher("home.jsp").forward(req, resp);
			}
			else if(command.equals("/boardFormProc.bo")) {
				Board2 board = new Board2();
				
				String uploadPath = req.getRealPath("upload");;
				
				int size = 10*1024*1024;
				
				MultipartRequest multi = new MultipartRequest(req, uploadPath, size,
						"euc-kr", new DefaultFileRenamePolicy());
				
				/////////
				//String file = multi.getFilesystemName(file1);
				//String origfilename1 = multi.getOriginalFileName(file1);
				////////
				
				
				
				board.setId(multi.getParameter("id"));
				board.setPass(multi.getParameter("pass"));
				board.setSubject(multi.getParameter("subject"));
				board.setContent(multi.getParameter("content"));
				board.setFile(multi.getFilesystemName("file"));
				//Enumeration files = multi.getFileNames();
				//String file1 = (String)files.nextElement();
				//board.setFile(multi.getFilesystemName("file1"));
					
				
				
				Board2DAOIbatis.insertBoard2(board);
				resp.sendRedirect("boardList.bo");
				
			} else if(command.equals("/boardList.bo")) {
				ArrayList<Board2> list = 
						(ArrayList<Board2>) Board2DAOIbatis.selectAllBoard2();
				req.setAttribute("list", list);
				req.setAttribute("body", "board/boardList.jsp");
				req.getRequestDispatcher("home.jsp").forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 	
	}
}
